<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-input v-model="search" placeholder="请输入关键字" class="handle-input mr10" clearable></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addUser" style="width: 150px;float: right">添加新用户 </el-button>
      </div>
      <el-table :data="userData" border style="width: 100%" class="table">
        <el-table-column prop="num" label="用户编号" align="center"/>
        <el-table-column prop="name" label="用户姓名" align="center"/>
        <el-table-column prop="pwd" label="用户密码" align="center"/>
        <el-table-column prop="authority" label="用户权限" align="center"/>
        <el-table-column prop="highPwd" label="高级密码" align="center"/>
        <el-table-column prop="depart" label="用户所在部门名" align="center"/>
        <el-table-column prop="note" label="用户信息说明" align="center" width="300px"/>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination :total="total" :current-page="currentPage" :page-size="currentPageSize" :page-sizes="[3,6,10]"
                       layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChange" @current-change="pageChange">
        </el-pagination>
      </div>
    </div>

    <!-- 添加弹出框 -->
    <el-dialog title="添加用户信息" v-model="addUserVisible" width="50%">
      <el-form ref="addUserform" :model="addUserform" label-width="150px">
        <el-form-item label="用户编号：" prop="num">
          <el-input v-model="addUserform.num"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名：" prop="name">
          <el-input v-model="addUserform.name"></el-input>
        </el-form-item>
        <el-form-item label="用户权限：" prop="authority">
          <el-select v-model="addUserform.authority" placeholder="请选择用户权限">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户密码：" prop="pwd">
          <el-input type="password" v-model="addUserform.pwd" show-password></el-input>
        </el-form-item>
        <el-form-item label="用户高级密码：" prop="highPwd" v-show="addUserform.authority == '管理员'">
          <el-input type="password" v-model="addUserform.highPwd" show-password></el-input>
        </el-form-item>
        <el-form-item label="用户所在部门名称：" prop="depart">
          <el-select v-model="addUserform.depart" placeholder="请选择用户所在部门">
            <el-option v-for="item in deparOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户信息说明：" prop="note">
          <el-input type="textarea" v-model="addUserform.note" :autosize="{minRows: 1, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addUserVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUserFunc">确 定</el-button>
                </span>
      </template>
    </el-dialog>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑用户信息" v-model="editVisible" width="50%">
      <el-form ref="form" :model="form" label-width="150px">
        <el-form-item label="用户编号：" prop="num">
          <el-input v-model="form.num" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名：" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="用户权限：" prop="authority">
          <el-input v-model="form.authority" style="width: 77%" :disabled="true"/>
          <el-button type="primary" icon="el-icon-edit-outline" style="margin-left: 10px; width: 121px" @click="editAuthority">修改权限</el-button>
        </el-form-item>
        <el-form-item label="用户密码：" prop="pwd">
          <el-input type="password" v-model="form.pwd"></el-input>
        </el-form-item>
        <el-form-item label="管理员高级密码：" prop="highPwd" v-show="form.authority == '管理员'">
          <el-input type="password" v-model="form.highPwd"></el-input>
        </el-form-item>
        <el-form-item label="用户所在部门名称：" prop="depart">
          <el-select v-model="form.depart" placeholder={{form.depart}}}>
            <el-option v-for="item in deparOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户信息说明：" prop="note">
          <el-input type="textarea" v-model="form.note" :autosize="{minRows: 1, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
      </template>
    </el-dialog>
    <!--修改权限弹出框-->
    <el-dialog title="修改用户权限" v-model="authorityVisible" width="40%" top="10%">
      <el-form ref="authorityForm" :model="authorityForm" label-width="130px">
        <el-form-item label="用户编号：" prop="num">
          <el-input v-model="form.num" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户密码：" prop="pwd">
          <el-input type="password" v-model="form.pwd" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户权限：" prop="authority">
          <el-select v-model="authorityForm.authority" placeholder="请选择用户权限">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员高级密码：" prop="highPwd" v-show="authorityForm.authority == '管理员'">
          <el-input type="password" v-model="authorityForm.highPwd" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="authorityVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveAuthority">确 定</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {getAllUsers, editAuthority, editUser, addUser, delUser, getAllDeparts} from "../../api/api";
export default {
  data() {
    return {
      addUserVisible: false,
      authorityVisible: false,
      search: "",
      currentPage: 1,
      currentPageSize: 6,
      total: null,
      tableData: [],
      userData: [],
      editVisible: false,
      form: {},
      authorityForm: {},
      addUserform: {},
      deparOptions:[],
      options: [{value: '管理员', label: '管理员'},
          {value: '普通用户', label: '普通用户'}],
      id: -1,//删除的记录
      idx: -1// 编辑的记录
    };
  },
  created() {
    this.getData();
    this.getDeparts();
  },
  methods: {
    //获取所有部门
    getDeparts(){
      getAllDeparts().then(res=>{
        console.log('res.data:', res.data)
        res.data.data.forEach(item =>{
          let depart = {
            'value': item.sdDepartmentName,
            'label': item.sdDepartmentName
          }
          this.deparOptions.push(depart)
        })
      })
    },
    // 添加新用户
    addUserFunc() {
      let y = {
        sdUserId: this.addUserform.num,
        sdUserName: this.addUserform.name,
        sdUserInfo: this.addUserform.note,
        sdUserAuthority: this.addUserform.authority == '管理员' ? 1: 2,
        sdUserSeniorPassword: this.addUserform.authority == '管理员' ? this.addUserform.highPwd : null,
        sdUserPassword: this.addUserform.pwd,
        sdUserDepartMentName: this.addUserform.depart
      }
      console.log('添加的用户信息：',y)
      addUser(y).then(res => {
        console.log('添加用户接口信息：', res.data)
        if (res.data.status == 200){
          this.addUserVisible = false
          this.$message.success('添加用户成功！')
          this.getData()
          this.addUserform = {}
        }else{
          this.$message.error('添加用户失败')
        }
      })
    },
    addUser(){
      this.addUserVisible = true
    },
    handleClick(row) {
      this.sheetVisible = true
      console.log(row);
    },
    // 模糊搜索
    searchList() {
        if (this.tableData.length > 0){
          let pageData = this.tableData.filter((item) =>
              item.num.includes(this.search)||
              item.name.includes(this.search)||
              item.pwd.includes(this.search)||
              item.authority.includes(this.search)||
              item.depart.includes(this.search)||
              item.note.includes(this.search)
          )
          this.userData = pageData.filter((item, index) =>
              index < this.currentPage * this.currentPageSize && index >= this.currentPageSize * (this.currentPage - 1)
          )
          this.total = pageData.length
        }
    },
    // 获取所有用户数据
    getData() {
      getAllUsers().then((res) =>{
        console.log('res.data', res.data)
        if (res.data.code == 403){
          this.$router.push('/')
        }else{
          this.tableData = []
          res.data.data.forEach((item) => {
            let add = {
              num: item.sdUserId,
              name: item.sdUserName,
              pwd: item.sdUserPassword,
              authority: item.sdUserAuthority == 1? '管理员':'普通用户',
              highPwd: item.sdUserSeniorPassword,
              depart: item.sdUserDepartMentName,
              note: item.sdUserInfo
            }
            this.tableData.push(add)
          })
          this.searchList()
        }
      })
    },
    // 编辑按钮点击确定
    saveEdit(){
      let y = {
        sdUserId:this.form.num,
        sdUserName: this.form.name,
        sdUserInfo: this.form.note,
        sdUserPassword: this.form.pwd,
        sdUserSeniorPassword: this.form.authority == '管理员' ? this.form.highPwd : null,
        sdUserDepartMentName:this.form.depart
      }
      editUser(y).then(res=>{
        console.log('编辑用户接口信息：', res.data)
        if (res.data.status == 403){
          this.$router.push('/login')
        }
        if (res.data.status == 200){
          this.editVisible = false
          this.form = {}
          this.$message.success(`修改第 ${this.idx + 1} 行用户信息成功!`);
          this.getData()
        }else{
          this.$message.error(`修改第 ${this.idx + 1} 行用户信息失败!`);
        }
      })
    },
    // 触发编辑权限按钮
    editAuthority(row) {
      this.authorityVisible = true
      console.log('this.form', this.form)
    },
    // 确定修改用户权限
    saveAuthority() {
      console.log('this.authorityForm', this.authorityForm)
      let y = {
        sdUserId: this.form.num,
        sdUserPassword: this.form.pwd,
        sdUserAuthority: this.authorityForm.authority == '管理员' ? 1 : 2,
        sdUserSeniorPassword: this.authorityForm.authority == '管理员' ? this.authorityForm.highPwd : null
      }
      editAuthority(y).then(res=>{
        console.log('res.data', res.data)
        if (res.data.status == 200){
          this.$message.success('修改用户权限成功！')
          this.authorityVisible = false
          console.log('此时的y', y)
          console.log('开始的form：', this.form)
          if (y.sdUserAuthority == 2){
            this.form.authority = '普通用户'
          }
          if (y.sdUserAuthority == 1){
            this.form.authority = '管理员'
            this.form.highPwd = y.sdUserSeniorPassword
          }
          console.log('此时的form表单', this.form)
        }else{
          this.$message.error('修改用户权限失败！')
        }
      })
    },
    // 触发搜索按钮
    handleSearch() {
      this.currentPage = 1
      this.searchList();
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      this.form = row;
      this.editVisible = true;
    },
    // 删除用户
    handleDelete(index){
      const idx = (this.currentPage - 1) * this.currentPageSize  + index //需要删除的记录所在行（从0开始）
      const delNum = this.tableData[idx].num
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning"
      }).then(() => {
        delUser(delNum).then((res) =>{
          console.log('信息：', res.data)
          if (res.data.code == 401){
            this.$router.push('/')
          }
          if(res.data.status == 200){
            this.$message.success("删除成功");
            this.$message.success(`修改第 ${this.idx + 1} 行用户信息成功!`);
            this.getData()
          }else{
            this.$message.error('删除失败！')
          }
        })
      }).catch(() => {

      });
    },
    //当每页数量改变
    pageSizeChange(size) {
      this.currentPageSize = size
      this.searchList()
    },
    // 当当前页改变
    pageChange(page) {
      this.currentPage = page
      this.searchList()
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
